<?php

namespace app\admin\controller\app;

use app\admin\model\AppIpConfig;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnotation;
use app\common\service\IpConfigService;
use think\App;

/**
 * @ControllerAnnotation(title="app_ip_config")
 */
class IpConfig extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\AppIpConfig();

        $this->assign('select_list_route_load_type', $this->model::SELECT_LIST_ROUTE_LOAD_TYPE, true);
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $model_config = AppIpConfig::where('uid', $post['uid'])->find();

                if (!empty($model_config)) {
                    throw new \Exception("配置ID不能重复", 1);
                }

                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {

                $model_config = AppIpConfig::where('uid', $post['uid'])->where('id', '<>', $id)->find();

                if (!empty($model_config)) {
                    throw new \Exception("配置ID不能重复", 1);
                }

                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function read($id)
    {

        $model_config = AppIpConfig::find($id);


        $service_ip_config = new IpConfigService($model_config);

        $list_record = $service_ip_config->buildPreviewMap();
        $list_listen_rules = $service_ip_config->buildFalseRangeIptablesRules();

        $this->assign('list_listen_rules', $list_listen_rules);
        $this->assign('list_record', $list_record);
        $this->assign('model_config', $model_config);

        return $this->fetch();
    }
}
